﻿using System;
using System.Collections.Generic;

namespace BlockOS.Collections
{
    public class IdentifierDictionary<T>
    {
        private readonly Dictionary<string, int> mapping;
        private readonly List<T> values;

        private readonly Queue<int> holes;

        public T this[Identifier id]
        {
            get
            {
                if (id.index == -1) id.index = mapping[id.id];
                return values[id.index];
            }
            set
            {
                if (id.index == -1) id.index = mapping[id.id];
                values[id.index] = value;
            }
        }

        public IdentifierDictionary()
        {
            mapping = new();
            values = new();
            holes = new();
        }

        public void Add(Identifier id, T value)
        {
            int index;
            if (holes.Count == 0)
            {
                index = values.Count;
                values.Add(value);
            }
            else
            {
                index = holes.Dequeue();
                values[index] = value;
            }
            id.index = index;
            mapping.Add(id.id, index);
        }

        public void Remove(Identifier id)
        {
            if (!mapping.ContainsKey(id.id)) return;

            var index = mapping[id.id];

            if (index == values.Count - 1)
            {
                values.RemoveAt(index);
            }
            else
            {
                holes.Enqueue(index);
                values[index] = default;
            }

            mapping.Remove(id.id);
        }
    }
}
